import QtQuick
import QtQuick.Layouts
import QtCharts

Rectangle {
    Layout.fillWidth: true
    Layout.fillHeight: true

    // 1. 数据
    property var stockData: [
        { year: 2025, month: 10, day: 3, open: 690, high: 694, low: 650, close: 660 },
        { year: 2025, month: 10, day: 4, open: 669, high: 720, low: 640, close: 710 },
        { year: 2025, month: 10, day: 5, open: 715, high: 740, low: 698, close: 705 },
        { year: 2025, month: 10, day: 6, open: 705, high: 750, low: 685, close: 738 },
        { year: 2025, month: 10, day: 7, open: 735, high: 745, low: 620, close: 640 },
        { year: 2025, month: 10, day: 10, open: 628, high: 650, low: 590, close: 645 },
        { year: 2025, month: 10, day: 11, open: 648, high: 668, low: 635, close: 655 },
        { year: 2025, month: 10, day: 12, open: 650, high: 680, low: 640, close: 675 },
        { year: 2025, month: 10, day: 13, open: 678, high: 690, low: 662, close: 685 },
        { year: 2025, month: 10, day: 14, open: 688, high: 698, low: 680, close: 692 },
        { year: 2025, month: 10, day: 17, open: 695, high: 710, low: 685, close: 705 },
        { year: 2025, month: 10, day: 18, open: 708, high: 720, low: 695, close: 715 },
        { year: 2025, month: 10, day: 19, open: 718, high: 728, low: 710, close: 720 },
        { year: 2025, month: 10, day: 20, open: 722, high: 735, low: 718, close: 730 },
        { year: 2025, month: 10, day: 21, open: 732, high: 745, low: 725, close: 738 },
        { year: 2025, month: 10, day: 24, open: 740, high: 748, low: 730, close: 735 },
        { year: 2025, month: 10, day: 25, open: 738, high: 742, low: 720, close: 725 },
        { year: 2025, month: 10, day: 26, open: 728, high: 735, low: 715, close: 720 },
        { year: 2025, month: 10, day: 27, open: 722, high: 730, low: 710, close: 715 },
        { year: 2025, month: 10, day: 28, open: 718, high: 725, low: 705, close: 710 }
    ]

    // 2. 处理函数
    function processStockData() {
        console.log("开始处理数据，数据条数：", stockData.length)

        // 清空旧数据
        candleSeries.clear()

        let minTime = Number.POSITIVE_INFINITY
        let maxTime = Number.NEGATIVE_INFINITY
        let minPrice = Number.POSITIVE_INFINITY
        let maxPrice = Number.NEGATIVE_INFINITY

        // 遍历数据创建K线
        for (let i = 0; i < stockData.length; i++) {
            const item = stockData[i]
            const date = new Date(item.year, item.month - 1, item.day)
            const timestamp = date.getTime()

            // 边界检查
            if (isNaN(timestamp)) {
                console.error("日期解析失败:", item)
                continue
            }

            minTime = Math.min(minTime, timestamp)
            maxTime = Math.max(maxTime, timestamp)
            minPrice = Math.min(minPrice, item.low)
            maxPrice = Math.max(maxPrice, item.high)

            // 创建CandlestickSet并检查是否成功
            const candleSet = candleSetComponent.createObject(candleSeries, {
                timestamp: timestamp,
                open: item.open,
                high: item.high,
                low: item.low,
                close: item.close
            })

            if (candleSet) {
                candleSeries.append(candleSet)
            } else {
                console.error("创建CandlestickSet失败:", item)
            }
        }

        // 检查是否有有效数据
        if (candleSeries.count === 0) {
            console.error("警告：没有成功添加任何数据")
            return
        }

        // 设置坐标轴范围
        dateAxisX.min = new Date(minTime)
        dateAxisX.max = new Date(maxTime)

        priceAxisY.min = Math.floor(minPrice / 10) * 10 - 10
        priceAxisY.max = Math.ceil(maxPrice / 10) * 10 + 10

        console.log("数据处理完成，共添加", candleSeries.count, "条K线")
        console.log("价格范围:", priceAxisY.min, "-", priceAxisY.max)
    }

    ChartView {
        id: chartView
        title: "股价走势图"
        titleFont.bold: true
        titleFont.pointSize: 14

        anchors.fill: parent
        antialiasing: true
        legend.visible: true
        legend.alignment: Qt.AlignBottom

        // Y轴
        ValueAxis {
            id: priceAxisY
            titleText: "股价 (元)"
            tickCount: 10
            labelFormat: "%.0f"
        }

        // X轴
        DateTimeAxis {
            id: dateAxisX
            titleText: "交易日期"
            format: "MM-dd"
            min: new Date(2025, 0, 1)
            max: new Date(2025, 0, 30)
        }

        CandlestickSeries {
            id: candleSeries
            name: "日K线"

            axisX: dateAxisX
            axisY: priceAxisY

            increasingColor: "#00C853"  // 阳线
            decreasingColor: "#FF3D00"  // 阴线
            bodyOutlineVisible: true
            capsVisible: true

            onClicked: function(candlestickSet, index) {
                const date = new Date(candlestickSet.timestamp)
                const change = candlestickSet.close - candlestickSet.open
                const changePercent = (change / candlestickSet.open * 100).toFixed(2)

                console.log(`${date.getMonth() + 1}月${date.getDate()}日 交易详情`)
                console.log(`${change >= 0 ? "上涨" : "下跌"} ${Math.abs(changePercent)}%`)
                console.log(`开盘: ${candlestickSet.open}元`)
                console.log(`收盘: ${candlestickSet.close}元`)
                console.log(`最高: ${candlestickSet.high}元`)
                console.log(`最低: ${candlestickSet.low}元`)
                console.log("----------------------------")
            }
        }

        // 动态组件
        Component {
            id: candleSetComponent
            CandlestickSet {}
        }

        // 确保组件完全就绪后再处理数据
        Component.onCompleted: {
            // 使用Qt.callLater确保所有组件初始化完成
            Qt.callLater(processStockData)
        }
    }
}
